import 'dart:async';
import 'package:flutter/material.dart';
import 'side_menu_controller.dart';
import 'menu_item_model.dart';
import 'menu_level_three.dart';

class MenuLevelTwo extends StatefulWidget {
  final MenuItemModel menuItem;
  final Color selectedColor;
  final Color hoverColor;
  final Color textColor;
  final Color selectedTextColor;
  final SideMenuController controller;
  final bool isCollapsed;
  
  const MenuLevelTwo({
    super.key,
    required this.menuItem,
    required this.selectedColor,
    required this.hoverColor,
    required this.textColor,
    required this.selectedTextColor,
    required this.controller,
    this.isCollapsed = false,
  });

  @override
  State<MenuLevelTwo> createState() => _MenuLevelTwoState();
}

class _MenuLevelTwoState extends State<MenuLevelTwo> {
  bool isHovered = false;
  bool isOverlayHovered = false;
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();
  Timer? _closeTimer;
  
  @override
  void dispose() {
    _removeOverlay();
    _closeTimer?.cancel();
    super.dispose();
  }
  
  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
  
  void _cancelCloseTimer() {
    _closeTimer?.cancel();
    _closeTimer = null;
  }
  
  void _showOverlay(BuildContext context) {
    if (widget.menuItem.children.isEmpty) return;
    
    _removeOverlay(); // 确保不会创建多个overlay
    
    _overlayEntry = OverlayEntry(
      builder: (context) {
        return Positioned(
          width: 200,
          child: CompositedTransformFollower(
            link: _layerLink,
            targetAnchor: Alignment.centerRight,
            followerAnchor: Alignment.centerLeft,
            offset: const Offset(5, 0),
            child: MouseRegion(
              onEnter: (_) {
                setState(() {
                  isOverlayHovered = true;
                });
                _cancelCloseTimer();
              },
              onExit: (_) {
                setState(() {
                  isOverlayHovered = false;
                });
                _startCloseTimer();
              },
              child: Material(
                elevation: 4.0,
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFF374A5E),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: widget.menuItem.children.map((item) {
                      return MenuLevelThree(
                        menuItem: item,
                        selectedColor: widget.selectedColor,
                        hoverColor: widget.hoverColor,
                        textColor: widget.textColor,
                        selectedTextColor: widget.selectedTextColor,
                        controller: widget.controller,
                        onMenuItemClick: () {
                          // 关闭所有菜单弹出层
                          _removeOverlay();
                          widget.controller.setHoveredLevelTwo(null);
                        },
                      );
                    }).toList(),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
    
    Overlay.of(context).insert(_overlayEntry!);
  }
  
  void _startCloseTimer() {
    _closeTimer?.cancel();
    _closeTimer = Timer(const Duration(milliseconds: 100), () {
      if (!isHovered && !isOverlayHovered) {
        _removeOverlay();
        widget.controller.setHoveredLevelTwo(null);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final isSelected = widget.controller.isMenuItemSelected(widget.menuItem.id);
    
    // 定义颜色，确保悬停颜色足够明显
    final effectiveHoverColor = Color.lerp(widget.hoverColor, widget.selectedColor, 0.3);
    
    return CompositedTransformTarget(
      link: _layerLink,
      child: MouseRegion(
        onEnter: (event) {
          setState(() {
            isHovered = true;
          });
          _cancelCloseTimer();
          widget.controller.setHoveredLevelTwo(widget.menuItem.id);
          if (widget.menuItem.hasChildren) {
            _showOverlay(context);
          }
        },
        onExit: (event) {
          setState(() {
            isHovered = false;
          });
          _startCloseTimer();
        },
        child: InkWell(
          onTap: () {
            if (!widget.menuItem.hasChildren) {
              widget.controller.selectMenuItem(widget.menuItem.id, route: widget.menuItem.route);
              _removeOverlay();
            }
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 150),
            decoration: BoxDecoration(
              color: isSelected 
                  ? widget.selectedColor 
                  : (widget.controller.hasSelectedChild(widget.menuItem))
                    ? widget.selectedColor
                    : (isHovered ? effectiveHoverColor : null),
              border: isHovered && !isSelected && !widget.controller.hasSelectedChild(widget.menuItem)
                  ? Border(
                      left: BorderSide(
                        color: widget.selectedColor,
                        width: 3,
                      ),
                    )
                  : null,
            ),
            padding: const EdgeInsets.only(left: 40, right: 16, top: 10, bottom: 10),
            child: Row(
              children: [
                Icon(
                  widget.menuItem.icon,
                  size: 16,
                  color: isSelected ? widget.selectedTextColor : widget.textColor,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    widget.menuItem.title,
                    style: TextStyle(
                      color: isSelected ? widget.selectedTextColor : widget.textColor,
                      fontSize: 14,
                      fontWeight: isHovered || isSelected || widget.controller.hasSelectedChild(widget.menuItem) 
                          ? FontWeight.bold 
                          : FontWeight.normal,
                    ),
                  ),
                ),
                if (widget.menuItem.hasChildren)
                  Icon(
                    Icons.arrow_right,
                    size: 16,
                    color: isSelected ? widget.selectedTextColor : widget.textColor,
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}